<template>
	<view class="page">
		<view class="courseware-list-box">
			<view v-for="(item, index) in coursewareList" :key="index" class="">
				<view class="time f_24 f_normal">{{ setTime(item.createtime, 'yyyy-MM-dd hh:ss') }}</view>
				<view class="info">
					<view class="dis-flex flex-y-center info-b-b">
						<view class="teacher-image"><image :src="item.teacher.headeravatar" lazy-load mode="aspectFill"></image></view>
						<view class="teacher-name f_24 f_normal">
							{{ item.teacher.teacher_course.grade.title }}{{ item.teacher.teacher_course.language.title }}{{ item.teacher.nickname }}
						</view>
					</view>
					<view class="dis-flex flex-y-center info-b-b onelist-hidden">
						<view class="courseware-image"><image :src="imgPrefix(getCoverImg(item.file))" lazy-load mode="aspectFill"></image></view>
						<view class="courseware-name f_32 f_normal">{{ item.filename }}</view>
					</view>
					<view class="btn-box f_24 f_normal flex-x-end dis-flex"><view class="btn" @tap="bindCourseware(item)">查看</view></view>
				</view>
			</view>

			<load-more :status="loadState" defaultIcon="1" text="暂无教师给您发课件"></load-more>
		</view>
	</view>
</template>

<script>
const app = getApp();
import { random_string, format, deepClone } from '@/static/uitls/common.js';
import { changeFormat } from '@/static/mixins/changeFormat.js';
import loadMore from '@/components/loadmore/index.vue';
import API from '@/static/api/index.js';
let downloadTask = '';
export default {
	name: 'my-courseware',
	mixins: [changeFormat],
	components: {
		loadMore
	},
	data() {
		return {
			isDown: false,
			loadState: 'loading',
			coursewareList: [],
			page: 1,
			size: 10,
			totals: 0,
			isRequest: false,
			downloadFile: {} //当前页面已经下载了的文件 在当前页面下保存，离开时丢弃
		};
	},
	onLoad() {
		this.refresh();
		if (!uni.getStorageSync('file_list')) {
			//没有就初始化
			uni.setStorageSync('file_list', JSON.stringify([]));
		}
		this.storageFileList = JSON.parse(uni.getStorageSync('file_list'));
	},
	methods: {
		// 获取文件后缀
		getExtensionName(file) {
			return file.substring(file.lastIndexOf('.'), file.length);
		},
		// 获取封面图片
		getCoverImg(file) {
			let extension = this.getExtensionName(file);
			let formatName = '';
			if (extension.indexOf('doc') != -1) {
				formatName = 'word';
			} else if (extension.indexOf('ppt') != -1 || extension.indexOf('pptx') != -1) {
				formatName = 'ppt';
			} else if (extension.indexOf('xlsx') != -1 || extension.indexOf('exe') != -1 || extension.indexOf('EXE') != -1) {
				formatName = 'excel';
			} else if (extension.indexOf('pdf') != -1) {
				formatName = 'pdf';
			}
			return '/static/image/teacher/' + formatName + '.png';
		},
		// 刷新
		refresh() {
			app._log(123);
			if (!this.isDown) {
				// 没有上传中或上传失败的，避免选择文件后进入
				this.isRequest = false;
				this.page = 1;
				this.studentCourseWare();
			}
		},

		// 文件分页请求
		studentCourseWare() {
			let { isRequest, page, size, coursewareList } = this;
			if (!isRequest && (coursewareList.length < this.totals || page == 1)) {
				this.isRequest = true;
				this.loadState = 'loading';
				API.studentCourseWare(page, size).then(({ code, data }) => {
					if (code == 1) {
						data.files.forEach(e => {
							e.select = false;
						});
						let tempArr = (page == 1 ? [] : coursewareList).concat(deepClone(data.files));
						this.coursewareList = tempArr;
						this.totals = data.total;
						this.loadState = tempArr.length >= data.total ? 'nomore' : 'getmore';
						if (data.total > tempArr.length) {
							this.page += 1;
						}
					} else if (code == 405 && page == 1) {
						this.loadState = 'empty';
						this.coursewareList = [];
					} else {
						this.loadState = 'error';
					}
					app._log(code, data);
					this.isRequest = false;
				});
			}
		},

		//判断数组对象中有没有存在某个键值
		JudgingISExistence(arr, keyName, keyData) {
			//数组 键名 键值
			return arr.findIndex(o => o[keyName] == keyData);
		},

		// 点击下载文件 ==》1
		bindCourseware({ file, size, filename }) {
			let _this = this;
			let { storageFileList } = _this;
			let index = this.JudgingISExistence(storageFileList, 'file', file);
			app._log('存在不', index);
			if (index != -1) {
				// 已经下载过该文件

				let { tempFilePath, savedFilePath } = storageFileList[index];
				if (savedFilePath != '') {
					//有本地文件路径
					uni.getFileInfo({
						filePath: savedFilePath,
						success: res => {
							app._log('下载过该文件了', res);
							if (res.errMsg == 'getFileInfo:ok') {
								// 文件存在
								this.openDocument(savedFilePath); //直接打开
							} else {
								//有记录但是文件丢失等报错
								this.startDownloading(file, size, filename); // 开始下载
							}
						},
						fail: err => {
							// 文件丢失等原因重新下载
							this.startDownloading(file, size, filename); // 开始下载
						}
					});
				} else if (tempFilePath != '') {
					//有临时文件路径
					_this.saveFile(file, size, tempFilePath, filename); //保存并打开文件
				} else {
					this.startDownloading(file, size, filename); // 开始下载
				}
			} else {
				// 没有下载过该文件
				if (size > 1024 * 1024 * 9) {
					uni.setClipboardData({
						data: file.toString(),
						success: res => {
							this.showToast('复制成功，请在浏览器打开');
						},
						catch: err => {
							this.showToast('复制失败');
						}
					});
				} else {
					this.startDownloading(file, size, filename); // 开始下载
				}
			}
		},

		// 开始下载==》2
		startDownloading(file, size, filename) {
			let _this = this;
			let { isDown } = _this;
			if (isDown) {
				this.showToast('您当前正在下载，请稍后再试');
			} else {
				this.showToast('正在下载' + filename);
				_this.isDown = true;
				this.clearFile({ fileSize: size, clearType: 0 }, status => {
					this.downFide(file, size, filename);
				});
			}
		},
		//清除已下文件
		clearFile({ fileSize, clearType }, success) {
			//clearType 0 容量达到临界清除  1 直接清除  fileSize文件大小
			uni.getSavedFileList({
				success: ({ errMsg = '', fileList = [] }) => {
					app._log(errMsg, fileList);
					if (errMsg == 'getSavedFileList:ok') {
						app._log(errMsg, fileList);
						app._log('已经下载了的文件列表', fileList);
						let maxSize = 0;
						if (clearType == 0 && fileList.length > 0) {
							//达到临界清除和文件不为空
							fileList.forEach(e => {
								maxSize += e.size;
							});
						}
						if (clearType == 1 || (clearType == 0 && Number(maxSize + fileSize) <= 6 * 1024 * 1024)) {
							// 容量超了或者强制清除
							fileList.forEach(e => {
								uni.removeSavedFile({ filePath: e.filePath });
							});
							this.storageFileList = [];
						}
						success && success(true);
					} else {
						success && success(false);
					}
				},
				fail: err => {
					app._log(err);
					success && success(false);
				}
			});
		},
		// 文件清除失败
		clearError(file, size, filename) {
			this.clearFile({ clearType: 0 }, status => {
				app._log(status);
				if (status) {
					// 清除成功
					// this.bindCourseware({status,file,size,filename})
				}
			});
		},
		// 单文件下载
		downFide(file, size, filename) {
			let _this = this;
			downloadTask = uni.downloadFile({
				url: file,
				success: ({ statusCode, tempFilePath }) => {
					if (statusCode === 200) {
						app._log('下载成功', tempFilePath);
						_this.storageFileList.push({ file: file, tempFilePath: tempFilePath, savedFilePath: '' });
						_this.isDown = false;
						_this.saveFile(file, size, tempFilePath, filename); //保存并打开
					} else {
						_this.showToast('下载失败');
						_this.isDown = false;
					}
				},
				fail: err => {
					app._log(err);
					_this.showToast('下载失败');
					_this.isDown = false;
				}
			});
			// downloadTask.onProgressUpdate((res) => {
			// 	app._log('下载进度' + res.progress);
			// 	app._log('已经下载的数据长度' + res.totalBytesWritten);
			// 	app._log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
			// });
		},
		// 保存单文件并打开
		saveFile(file, size, tempFilePath, filename) {
			let _this = this;
			uni.saveFile({
				tempFilePath,
				success: ({ savedFilePath }) => {
					_this.openDocument(savedFilePath);
					let index = _this.JudgingISExistence(_this.storageFileList, 'file', file);
					if (index != -1) {
						_this.storageFileList[index].savedFilePath = savedFilePath;
					}
				},
				fail: err => {
					app._log('文件保存失败', err);
					this.clearError(file, size, filename);
				}
			});
		},
		//打开文件
		openDocument(path) {
			uni.openDocument({
				filePath: path,
				success: respon => app._log('成功打开文档')
			});
		},
		// 中断下载任务
		abort() {
			downloadTask.abort();
		}
	},
	onHide() {
		uni.setStorageSync('file_list', JSON.stringify(this.storageFileList.filter(o => o.savedFilePath != '')));
	},
	beforeDestroy() {
		if (this.isDown) {
			downloadTask.abort();
		}
	}
};
</script>

<style scoped lang="scss">
.courseware-list-box {
	.time {
		color: #999999;
		padding: 24rpx 0;
		text-align: center;
	}
	.info {
		background-color: white;
		margin: 0 48rpx 24rpx 48rpx;
		box-shadow: 0rpx 0rpx 16rpx 0rpx rgba(37, 39, 72, 0.03);
		border-radius: 24rpx;
		.teacher-image image {
			width: 64rpx;
			height: 64rpx;
			border-radius: 16rpx;
			margin-right: 16rpx;
		}
		.teacher-name {
			color: #252748;
		}
		.courseware-image image {
			width: 96rpx;
			height: 96rpx;
			border-radius: 4rpx;
			margin-right: 16rpx;
		}
		.courseware-name {
			color: #1f2633;
		}
		.info-b-b {
			margin: 0 24rpx;
			padding: 24rpx 0;
			border-bottom: 1px solid rgba(204, 204, 204, 0.5);
		}
		.btn-box {
			padding: 16rpx 24rpx;
			.btn {
				display: inline-block;
				background-image: linear-gradient(314deg, #7f4aff 0%, #9254ff 100%);
				border-radius: 16rpx;
				color: #ffffff;
				padding: 16rpx 56rpx;
			}
		}
	}
}
</style>
